﻿using System;
using System.Linq;
using System.Web.Mvc;
using mytechblog.Managers;

namespace mytechblog.Controllers
{
	public class HomeController : Controller
	{
		public ActionResult Index()
		{
            var articles = DataManager.GetArticles();
            return View(articles);
		}

		public ActionResult About()
		{
			return View();
		}

		public ActionResult Article(int? ID)
		{
			const string errorMessage = "Sorry, article not found";
			if (ID == null)
			{
				return new HttpNotFoundResult(errorMessage);
			}
            var article = DataManager.GetArticle(ID.Value);
            if (article == null)
                return new HttpNotFoundResult(errorMessage);
            return View(article);
		}

		public ActionResult EditArticleList()
		{
			if (!HtmlHelperEx.IsDebug())
			{
				return new HttpNotFoundResult();
			}
            var articles = DataManager.GetArticlesToEdit();
            return View(articles);
		}

		public ActionResult Edit(int? ID)
		{
			if (!HtmlHelperEx.IsDebug())
			{
				return new HttpNotFoundResult();
			}
			if (ID == null)
			{
				return View(new Article());
			}
            var article = DataManager.GetArticle(ID.Value, true);
            if (article == null)
            {
                return new HttpNotFoundResult();
            }
            return View(article);
		}

		[HttpPost]
		public ActionResult Edit(Article article)
		{
			if (!HtmlHelperEx.IsDebug())
			{
				return new HttpNotFoundResult();
			}
			if (Request.IsAjaxRequest())
			{
				return Json(new { error = "not allowed" });
			}
            var articleId = DataManager.SaveArticle(article);
			return RedirectToAction("Edit", new { ID = articleId });
		}

		public ActionResult Articles()
		{
            var articles = DataManager.GetArticles();
            return PartialView(articles);
		}

		public ActionResult Categories()
		{
            var categories = DataManager.GetCategories();
            return PartialView(categories);
		}

        public ActionResult Category(int? ID)
        {
            const string errorMessage = "Sorry, category not found";
            if (ID == null)
            {
                return new HttpNotFoundResult(errorMessage);
            }
            var category = DataManager.GetCategory(ID.Value);
            if (category == null)
            {
                return new HttpNotFoundResult(errorMessage);
            }
            ViewBag.category = category;

            var articles = DataManager.GetArticles(ID.Value);
            if (articles == null)
            {
                return new HttpNotFoundResult(errorMessage);
            }
            return View(articles);
        }
	}
}
